<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 22:30:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-02 19:27:25
 * @Descripttion: 用户model
 */

namespace app\common\model;

use think\Model;

class UserManage extends Base
{
    /**
     * 通过token获取用户信息
     *
     * @param [type] $token
     * @return void
     */
    public function getToken($token)
    {
        if (empty($token)) {
            return false;
        }
        // $info = $this->where('id', 221)
     
        $info = $this->where('token',$token)
            ->field([
                'id', 'username','nickname','mobile','avatar','openid','unionid','client_id','is_del'
            ])
            ->find();
        if (empty($info)) {
            return false;
        }
        if ($info['is_del'] == 1) {
            return false;
        }
        return $info;
    }
    /**
     * 设置token
     *
     * @param [type] $id
     * @return void
     */
    public function setToken($id)
    {
        $account = $this->where(['id' => $id])->find();
        if (empty($account)) {
            return false;
        }
        if(!empty($account['username'])){
            $token_u = $account['username'];
        }
        if(!empty($account['openid'])){
            $token_u = $account['openid'];
        }
        $token = StrMD5($id . $token_u . '*p$h^p*');
        // $token = StrMD5($id . uniqid() . time());
        $this->where('id', $id)->update(['token' => $token]);
        return $token;
    }
    
    public function getAvatarTextAttr($value,$data){
        return $data['avatar'] ? cdnurl($data['avatar'],true) : "";
    }
    public function getIsDelTextAttr($value,$data){
        $arr = [0 => "正常" , 1 => "注销"];
        return $arr[$data['is_del']];
    }
    public function increase(){
        //积分增加
    }
    public function reduce($user_id,$money){
        //积分减少
        $user = (new \app\common\model\User())->where(['id' => $user_id])->find();
        $yu_e = $user['integral']-$money;
        if($yu_e >=0){
             (new \app\common\model\User())
                                ->where([
                                    'id' => $user_id,
                                    'integral' => $user['integral'],
                                    ])
                                ->update([
                                    'integral' => $yu_e
                                ]);
            return [
                'code' => 1,
                'msg' => '成功',
            ];
        }else{
            return [    
                'code' => 0,
                'msg' => '失败',
            ];
        }
    }
    public function getStatusTextAttr($value,$data){
        $arr = ['正常','封禁'];
        return $arr[$data['status']];
    }
    public function getCompanyTitleAttr($value,$data){
        return $data['company_id'] == 0 ? '' : (new \app\common\model\Company())->where(['id' => $data['company_id']])->value('title');
    }
}
